package com.servlet;

import com.dao.imp.AddUpdDelDaoImp;
import com.dao.imp.FindGoodsDaoImp;
import net.sf.json.JSONObject;

import javax.servlet.*;
import javax.servlet.http.*;
import javax.servlet.annotation.*;
import java.io.IOException;
import java.util.List;
import java.util.Map;

/**
 * @author Mathison
 * @Title: ${NAME}
 * @Package: ${PACKAGE_NAME}
 * @Description: TODO
 * @date 2021/11/27 19:15
 **/

@WebServlet(name = "UpdateTotalPriceServlet", value = "/UpdateTotalPriceServlet")
public class UpdateTotalPriceServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }

    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        HttpSession session = request.getSession();
        int user_id = Integer.parseInt(session.getAttribute("userId").toString());

        String sql = "SELECT * FROM shoppingchart WHERE user_id = "+user_id;

        FindGoodsDaoImp findGoodsDaoImp = new FindGoodsDaoImp();
        List<Map> goods = findGoodsDaoImp.findGoods(sql);
        int totalPrice = 0;
        for (int i = 0; i < goods.size(); i++) {
            int price = Integer.parseInt(goods.get(i).get("price").toString());
            int count = Integer.parseInt(goods.get(i).get("good_amount").toString());
            totalPrice += price*count;
        }

        JSONObject json = JSONObject.fromObject("{cartTotalPrice:"+totalPrice+"}");
        response.getWriter().print(json);
    }
}
